package com.glory.dgcpcpda.activity.mfg;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.dgcpcpda.R;
import com.glory.dgcpcpda.activity.MainActivity;
import com.glory.dgcpcpda.adapter.PMSchedulingAdapter;
import com.glory.dgcpcpda.base.BaseActivity;
import com.glory.dgcpcpda.base.Constant;
import com.glory.dgcpcpda.entity.EqpInfoEntity;
import com.glory.dgcpcpda.entity.MaintainEntity;
import com.glory.dgcpcpda.entity.response.BaseResponseBean;
import com.glory.dgcpcpda.utils.LotUtils;
import com.glory.dgcpcpda.utils.NetUtils;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.datepicker.CustomDatePicker;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DateUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_LogUtils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import butterknife.BindView;
import butterknife.OnClick;

public class PMSchedulingActivity extends BaseActivity implements BaseQuickAdapter.OnItemClickListener {


    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.etEqpID)
    FreeUI_ClearEditText etEqpID;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.tvLocation)
    TextView tvLocation;
    @BindView(R.id.tvDepartment)
    TextView tvDepartment;
    @BindView(R.id.tvEqpType)
    TextView tvEqpType;
    @BindView(R.id.rvMaintainList)
    RecyclerView rvMaintainList;
    @BindView(R.id.tvBeginTime)
    TextView tvBeginTime;
    @BindView(R.id.tvEndTime)
    TextView tvEndTime;

    private String eqpID = "";
    private PMSchedulingAdapter mSchedulingAdapter;
    private int p=-1;
    private ArrayList<MaintainEntity.PmsScheduleResults> xPmsScheduleResults;
    private CustomDatePicker mDatePicker;
    boolean isBegin;
    private String beginDate = "";
    private String endDate = "";

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_pm_scheduling;
    }

    @Override
    protected void initView() {
        tvTitle.setText("PM调度");
        setMainLayout(llMain);

        initRecyclerView(rvMaintainList, this);
        mSchedulingAdapter = new PMSchedulingAdapter(null);
        rvMaintainList.setAdapter(mSchedulingAdapter);
        mSchedulingAdapter.setOnItemClickListener(this);

//        ArrayList<MaintainEntity.PmsScheduleResults> pmsScheduleResults = new ArrayList<>();
//        MaintainEntity.PmsScheduleResults pmsScheduleResults1 = new MaintainEntity.PmsScheduleResults();
//        pmsScheduleResults1.setSheetName("aaaa");
//        pmsScheduleResults1.setPeriodId("bbbb");
//        pmsScheduleResults.add(pmsScheduleResults1);
//        mSchedulingAdapter.addData(pmsScheduleResults);

        Bundle bundle = getIntent().getExtras();
        eqpID = bundle.getString("EQPID");
        etEqpID.setText(eqpID);
        LotUtils.searchEqpInfo(eqpID, PMSchedulingActivity.this, getSupportFragmentManager(), new LotUtils.netCallback<EqpInfoEntity>() {
            @Override
            public void onSuccess(EqpInfoEntity response) {
                tvLocation.setText(response.getEQUIPMENT().getLOCATION());
                tvDepartment.setText(response.getEQUIPMENT().getDEPARTMENT());
                tvEqpType.setText(response.getEQUIPMENT().getEQPTYPE());
                getMaintainInfo(eqpID);
            }
            @Override
            public void onFail(Throwable t) {
                loadError(t,"EQPQUERY");
            }
        });
    }

    private void getMaintainInfo(String eqpID) {
        FreeUI_EntityCallBack<BaseResponseBean<MaintainEntity>> callback = new FreeUI_DialogEntityCallBack<BaseResponseBean<MaintainEntity>>
                (new TypeToken<BaseResponseBean<MaintainEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<MaintainEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), false, getSupportFragmentManager())) {
                    xPmsScheduleResults = response.body().getResponse().getBody().getXPmsScheduleResults();
                    mSchedulingAdapter.setNewData(xPmsScheduleResults);
                }
            }
            @Override
            public void onError(Response<BaseResponseBean<MaintainEntity>> response) {
                super.onError(response);
            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("actionType", "query");
        map.addProperty("eqpId", eqpID);
        if (beginDate.equals("") || endDate.equals("")){
            map.addProperty("startTime", FreeApi_DateUtils.getAfterStringDate(new Date(System.currentTimeMillis()), "yyyy-MM-dd", 0));
            map.addProperty("endTime", FreeApi_DateUtils.getAfterStringDate(new Date(System.currentTimeMillis()), "yyyy-MM-dd", 0));
        }else {
            map.addProperty("startTime", beginDate);
            map.addProperty("endTime", endDate);
        }
        NetUtils.requestPostNet("CPC.PMSSCHEDULE", "TRANSFERMES",this, map, callback);
    }

    @Override
    protected void initData() {
        initDatePicker();
    }

    private void initDatePicker() {
//        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
//        Date curDate = new Date(System.currentTimeMillis());
//        String str = formatter.format(curDate);

        long beginTimestamp = FreeApi_DateUtils.str2Long("2000-01-01", false);
        long endTimestamp = FreeApi_DateUtils.str2Long("2222-02-22", false);

        // 通过时间戳初始化日期，毫秒级别
        mDatePicker = new CustomDatePicker(this, timestamp -> {
            if (isBegin) {
                beginDate = FreeApi_DateUtils.long2Str(timestamp, false);
                tvBeginTime.setText(beginDate);
                getMaintainInfo(eqpID);
            } else {
                endDate = FreeApi_DateUtils.long2Str(timestamp, false);
                tvEndTime.setText(endDate);
                getMaintainInfo(eqpID);
            }

        }, beginTimestamp, endTimestamp);
        // 不允许点击屏幕或物理返回键关闭
        mDatePicker.setCancelable(true);
        // 不显示时和分
        mDatePicker.setCanShowPreciseTime(false);
        // 不允许循环滚动
        mDatePicker.setScrollLoop(false);
        // 不允许滚动动画
        mDatePicker.setCanShowAnim(false);
    }

    @OnClick({R.id.tvBaseSubmit,R.id.flBeginTimeList, R.id.flEndTimeList,})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.flBeginTimeList:
                isBegin = true;
                mDatePicker.show(System.currentTimeMillis());
                break;
            case R.id.flEndTimeList:
                isBegin = false;
                mDatePicker.show(System.currentTimeMillis());
                break;
            case R.id.tvBaseSubmit:
                MaintainEntity.PmsScheduleResults data = null;
                for (MaintainEntity.PmsScheduleResults adapterData : mSchedulingAdapter.getData()) {
                    if (adapterData.isCheck()) {
                        data = adapterData;
                    }
                }

                if (data == null) {
                    showToast("请选择保养数据", false);
                    return;
                }

                FreeUI_EntityCallBack<BaseResponseBean<JsonObject>> callback = new FreeUI_DialogEntityCallBack<BaseResponseBean<JsonObject>>
                        (new TypeToken<BaseResponseBean<JsonObject>>() {
                        }.getType(), getSupportFragmentManager(), this) {

                    @Override
                    public void onSuccess(Response<BaseResponseBean<JsonObject>> response) {
                        super.onSuccess(response);
                        if (response.body().isSuccess(getApplicationContext(), false, getSupportFragmentManager())) {
                            showToast("提交成功", false);
                            Intent intent = new Intent(PMSchedulingActivity.this, MainActivity.class);
                            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                        }
                    }

                    @Override
                    public void onError(Response<BaseResponseBean<JsonObject>> response) {
                        super.onError(response);
                    }
                };
                JsonObject map = new JsonObject();
                map.addProperty("ACTIONTYPE", "APPOINTLOGEVENT");
                map.addProperty("SCHEDULERRN", data.getScheduleRrn());
//        map.addProperty("APPOINT", data.getReserved8());
                map.addProperty("APPOINT", "已指派");
                NetUtils.requestPostNet("CPC.APPOINTLOGEVENT", "TRANSFERMES", this, map, callback);
                break;
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        if (p != -1 && p != position){
            xPmsScheduleResults.get(p).setCheck(false);
            xPmsScheduleResults.get(position).setCheck(true);
        }else {
            xPmsScheduleResults.get(position).setCheck(true);
        }

        p = position;
        mSchedulingAdapter.notifyDataSetChanged();
    }

    @Override
    protected void onResume() {
        super.onResume();
        getMaintainInfo(eqpID);
    }
}
